package com.service.socket.process;

import org.jboss.netty.channel.Channel;

import com.service.bean.Road_GpsSignal;
import com.service.bean.signal.GpsSignal;
import com.service.cache.CacheManager;
import com.service.other.Logger;
import com.service.socket.protocol.CmdWord;
import com.service.socket.protocol.Conversion;
import com.service.socket.protocol.Packet;

public class R_Class_E0 extends R_Class_Abstract {
	public R_Class_E0(Channel channel, Packet packet) {
		super(channel, packet);
	}

	@Override
	public void execute() {
		try {
			doQuery();
		} catch (Exception e) {
			Logger.err(e);
		}		
	}
	
	public void doQuery() {
		if (!packet.isCrcValid()) {
			packet.status = CmdWord.STATUS_FAIL;
			packet.dataArea = null;
			SendCommand.replyDtu(channel,packet);
			Logger.err("device [" + packet.getDeviceNo()+ "] regist fail on [isCrcValid]:" + packet.isCrcValid());
			return;
		}
		Packet bean = (Packet) packet.clone();
		bean.status = CmdWord.STATUS_SUCCESS;
		bean.dataArea = getDataArea(bean.dataArea);
		SendCommand.replyDtu_E0_NOSAVE(channel,bean);
	}
	
	public String getDataArea(String dataArea){		
		String str = new String(Conversion.hexStringToBytes(dataArea));
		str = getLastSignalsByJson(str);
		str = Conversion.bytesToHexString(str.getBytes());
		return str;
	}

	public String getLastSignalsByJson(String dataArea){
		String[] devices = dataArea.split(",");
		String json = "[";
		for(String deviceNo:devices){
			GpsSignal lastGps = null;
			if(CacheManager.instance().vehicleMap.containsKey(deviceNo)){
				lastGps = CacheManager.instance().vehicleMap.get(deviceNo).getLastGps_Received();				
				if(lastGps != null){
					if(json.equals("[")){
						//第一条记录
						json += "{" + lastGps.toString() + "}";
					}else{
						//第N条记录
						json += ",{" + lastGps.toString() + "}";
					}
				}
			}else{
				if(CacheManager.instance().roadVehicleMap.containsKey(deviceNo)){
					Road_GpsSignal road_lastGps = CacheManager.instance().roadVehicleMap.get(deviceNo).getLastGps_Received();				
					if(road_lastGps != null){
						if(json.equals("[")){
							//第一条记录
							json += "{" + road_lastGps.toString() + "}";
						}else{
							//第N条记录
							json += ",{" + road_lastGps.toString() + "}";
						}
					}
				}
			}
		}
		json += "]";

		return json;
	}
}
